package br.com.lupanar.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


public class DAO {

	private EntityManagerFactory emf;
	private EntityManager em;
	private EntityTransaction tra;

	public DAO() {

		emf = Persistence.createEntityManagerFactory("conexao");
		em = emf.createEntityManager();
	}

	public void salvar(Object entidade)   throws Exception{

		try {
			tra = em.getTransaction();

			tra.begin();
			em.persist(entidade);
			tra.commit();
		} catch (RuntimeException e) {
			
			if(tra != null && tra.isActive()) {
				tra.rollback();
			}
			
			throw new Exception(e);
		}
	}
	
	public void alterar(Object entidade) throws Exception {

		try {
			tra = em.getTransaction();

			tra.begin();
			em.merge(entidade);
			tra.commit();
		} catch (RuntimeException e) {
			if(tra != null && tra.isActive()) {
				tra.rollback();
			}
			
			throw new Exception(e);
		}
	}
	
	public void excluir(Object entidade) throws Exception {

		try {
			tra = em.getTransaction();

			tra.begin();
			em.remove(em.merge(entidade));
			tra.commit();
		} catch (RuntimeException e) {
			if(tra != null && tra.isActive()) {
				tra.rollback();
			}
			
			throw new Exception(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	public Object buscarPorId(Long id, Class classeDaEntidade) {
		return (Object) em.find(classeDaEntidade, id);
	}
}
